package com.styytech.dadabao.ui.project;

import android.graphics.drawable.Drawable;
import android.net.http.SslError;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lidroid.xutils.view.annotation.ViewInject;
import com.loopj.android.http.RequestParams;
import com.styytech.dadabao.R;
import com.styytech.dadabao.api.requestresult.ProductDetailMoreResult;
import com.styytech.dadabao.api.response.AbstractResponseResult;
import com.styytech.dadabao.api.templates.HttpRequest;
import com.styytech.dadabao.base.BaseFragment;
import com.styytech.dadabao.bean.RecommendProduct;
import com.styytech.dadabao.constant.ConstantsServerUrl;
import com.styytech.dadabao.exception.ArgumentsException;
import com.styytech.dadabao.exception.RequestException;
import com.styytech.dadabao.utils.CommonUtils;
import com.styytech.dadabao.widge.webview.InnerWebView;

public class MoreDetailDescriptionFragment extends BaseFragment {
    private View rootView;


    RecommendProduct userAccountOld;

    @ViewInject(R.id.ll_content)//下部内容
    private LinearLayout ll_content;
    private boolean isFrist = true;


    @ViewInject(R.id.tv_desc)//基础描述
    private TextView tv_desc;
    @ViewInject(R.id.wv_desc_content)//基础描述
    private InnerWebView wv_desc_content;


    @ViewInject(R.id.tv_info)//保理信息
    private TextView tv_info;
    @ViewInject(R.id.tv_info_content)//保理信息
    private TextView tv_info_content;


    @ViewInject(R.id.tv_trade_info)//基础交易材料
    private TextView tv_trade_info;
    @ViewInject(R.id.tv_trade_info_content)//基础交易材料
    private TextView tv_trade_info_content;


    @ViewInject(R.id.tv_risk_guarantee)//风险保障
    private TextView tv_risk_guarantee;
    @ViewInject(R.id.tv_risk_guarantee_content)//风险保障
    private TextView tv_risk_guarantee_content;


    @ViewInject(R.id.tv_factoring_business)//保理业务材料
    private TextView tv_factoring_business;
    @ViewInject(R.id.tv_factoring_business_content)//保理业务材料
    private TextView tv_factoring_business_content;


    public static MoreDetailDescriptionFragment newInstance(RecommendProduct userAccount) {
        MoreDetailDescriptionFragment fragment = new MoreDetailDescriptionFragment();

        Bundle bundle = new Bundle();
        bundle.putSerializable("userAccount", userAccount);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = super.onCreateView(inflater, container, savedInstanceState,
                R.layout.fragment_more_description);
        userAccountOld = (RecommendProduct) getArguments().getSerializable("userAccount");
        return rootView;
    }

    public void onResume() {
        getDetailMore();
        super.onResume();
    }

    /**
     * 重新加载
     */
    protected void reloadBtnOnclick() {
        isFrist = true;
        getDetailMore();
    }

    Html.ImageGetter imgGetter = new Html.ImageGetter() {
        @Override
        public Drawable getDrawable(String source) {
            Drawable drawable = null;
            drawable = Drawable.createFromPath(source);  // Or fetch it from the URL
            // Important
            if (drawable != null) {
                drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable
                        .getIntrinsicHeight());
            }
            return drawable;
        }
    };
/***************************** 更多信息描述 ***************************************/
    /**
     * 获取我账户信息
     */
    AbstractResponseResult responseResult = new AbstractResponseResult() {

        @Override
        public void executeSuccess(Object object) {
            RecommendProduct userAccount = (RecommendProduct) object;
            if (userAccount == null) {
                setView(View.VISIBLE, View.GONE, View.VISIBLE, View.VISIBLE, "描述信息获取失败");
            } else {
                setView(View.GONE, View.VISIBLE, View.VISIBLE, View.GONE, "");
                ll_content.setVisibility(View.VISIBLE);
            }

//            URLImageParser parser = new URLImageParser(tv_desc_content, context);
            tv_desc.setText(userAccountOld.getProductName() + "  基础信息");
//            Spanned text = Html.fromHtml(userAccount.getBasicInformation(),parser, null);
//            tv_desc_content.setText(text);
            //  tv_desc_content.setText(ToDBC(userAccount.getBasicInformation()) + "");
//            tv_desc_content.setText(Html.fromHtml(userAccount.getBasicInformation(),parser, null));
//            wv_desc_content.requestDisallowInterceptTouchEvent(false);
            wv_desc_content.setWebViewClient(new WebViewClient() {

                public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
//                    handler.cancel(); // Android默认的处理方式
                    handler.proceed();  // 接受所有网站的证书
                    //handleMessage(Message msg); // 进行其他处理
                }
            });

            wv_desc_content.getSettings().setJavaScriptEnabled(true);
            wv_desc_content.loadDataWithBaseURL("", userAccount.getBasicInformation(), "text/html", "UTF-8", "");


            tv_info.setText(userAccountOld.getProductName() + "  保理信息");
//            tv_info_content.setText(ToDBC(userAccount.getScienceInformation()) + "");
            tv_info_content.setText(Html.fromHtml(userAccount.getScienceInformation()));

            tv_trade_info.setText(userAccountOld.getProductName() + "  基础交易材料");
//            tv_trade_info_content.setText(ToDBC(userAccount.getBasicTrading()) + "");
            tv_trade_info_content.setText(Html.fromHtml(userAccount.getBasicTrading()));

            tv_risk_guarantee.setText(userAccountOld.getProductName() + "  风险保障");
//            tv_risk_guarantee_content.setText(ToDBC(userAccount.getRiskGuarantee()) + "");
            tv_risk_guarantee_content.setText(Html.fromHtml(userAccount.getRiskGuarantee()));


            tv_factoring_business.setText(userAccountOld.getProductName() + "  保理业务材料");
//            tv_factoring_business_content.setText(ToDBC(userAccount.getFactoringBusiness()) + "");
            tv_factoring_business_content.setText(Html.fromHtml(userAccount.getFactoringBusiness()));
        }

        @Override
        public void executeError(String message, int errorCode) {
            setView(View.VISIBLE, View.GONE, View.VISIBLE, View.VISIBLE, "");
        }

        @Override
        public void HttpError(String message, int errorCode) {
            setView(View.VISIBLE, View.GONE, View.VISIBLE, View.VISIBLE, "");
        }
    };

    public static String ToDBC(String input) {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 12288) {
                c[i] = (char) 32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375)
                c[i] = (char) (c[i] - 65248);
        }
        return new String(c);
    }

    public void getDetailMore() {
        if (userAccountOld == null) {
            CommonUtils.showToastMsg(getmActivity(), "项目信息错误");
            setView(View.VISIBLE, View.GONE, View.VISIBLE, View.VISIBLE, "描述信息获取失败");
            return;
        }

        if (isFrist) {
            setView(View.VISIBLE, View.VISIBLE, View.VISIBLE, View.GONE, "获取描述信息...");
            ll_content.setVisibility(View.GONE);

            isFrist = !isFrist;
        }

        String url = ConstantsServerUrl.getProductDetailMore();
        RequestParams params = new RequestParams();
        params.put("productId", userAccountOld.getId());

        ProductDetailMoreResult logResult = new ProductDetailMoreResult(responseResult);
        try {
            new HttpRequest(context).doPost(logResult, url, params);
        } catch (ArgumentsException e) {
            Log.i("INFO", "1e:" + e);
            e.printStackTrace();
        } catch (RequestException e) {
            Log.i("INFO", "2e:" + e);
            e.printStackTrace();
        }
    }

}
